var login_user = null;
jQuery(document).ready(function($){
    var $form_modal = $('.cd-user-modal'),
        $form_login = $form_modal.find('#cd-login'),
        $form_signup = $form_modal.find('#cd-signup'),
        $form_modal_tab = $('.cd-switcher'),
        $tab_login = $form_modal_tab.children('li').eq(0).children('a'),
        $tab_signup = $form_modal_tab.children('li').eq(1).children('a'),
        $main_nav = $('.main_nav');

    //弹出窗口
    $(".cd-signin").on('click', function(event){
        if( $(event.target).is($main_nav) ) {
            $(this).children('ul').toggleClass('is-visible');
        } else {
            $main_nav.children('ul').removeClass('is-visible');
            $form_modal.addClass('is-visible');
            ( $(event.target).is('.cd-signup') ) ? signup_selected() : login_selected();
        }
    });

    $(".cd-signup").on('click', function(event){
        if( $(event.target).is($main_nav) ) {
            $(this).children('ul').toggleClass('is-visible');
        } else {
            $main_nav.children('ul').removeClass('is-visible');
            $form_modal.addClass('is-visible');
            ( $(event.target).is('.cd-signup') ) ? signup_selected() : login_selected();
        }
    });

    //投稿按钮
    $(".cd-tougao").on('click', function(event){
        try_publish()
    });

    //关闭弹出窗口
    $('.cd-user-modal').on('click', function(event){
        if( $(event.target).is($form_modal) || $(event.target).is('.cd-close-form') ) {
            $form_modal.removeClass('is-visible');
        }
    });
    //使用Esc键关闭弹出窗口
    $(document).keyup(function(event){
        if(event.which=='27'){
            $form_modal.removeClass('is-visible');
        }
    });

    //切换表单
    $(".register-text").on('click', function(event) {
        debugger
        event.preventDefault();
        if($(this).hasClass("js-user-login")) {
            login_selected()
        } else{
            signup_selected();
        }
    });

    function login_selected(){
        $form_login.addClass('is-selected');
        $form_signup.removeClass('is-selected');
        $tab_login.addClass('selected');
        $tab_signup.removeClass('selected');
    }

    function signup_selected(){
        $form_login.removeClass('is-selected');
        $form_signup.addClass('is-selected');
        $form_forgot_password.removeClass('is-selected');
        $tab_login.removeClass('selected');
        $tab_signup.addClass('selected');
    }
    //注册新用户
    $(".js-btn-sms-login").click(function(){
        if( do_validate_user_info() ){
            do_regist_new_user();
        }
    });
    //登录系统
    $(".js-btn-login").click(function(){
        if( do_validate_login_info() ){
            do_login();
        }
    });
    //投稿按钮动作
    function try_publish(){
        $form_modal.removeClass('is-visible');
        //投稿 判断一下是否已经登录，如果登录过了，则打开发布页，如果未登录则打开登录页
        if( login_user == null ){
            var url = "/login_user?flag=" + new Date().getTime();
            send_get(url, function(json){
                debugger
                if ("success" != json.status || json.login_status == 0) {
                    login_user = json.login_user;
                    //显示登录页
                    $main_nav.children('ul').removeClass('is-visible');
                    $form_modal.addClass('is-visible');
                    login_selected();
                }else{
                    //加载文章发布页
                    load_main("main_article_edit.html?flag="+new Date().getTime())
                }
            })
        }else{
            //加载文章发布页
            load_main("main_article_edit.html?flag="+new Date().getTime())
        }
    }
    if( "index" == type ){
         list_articles(20);
    }

});

function list_articles(max_count, current_page){
    var url = "home/articles";
    var data = {
        "max_count" : max_count,
        "current_page" : current_page
    }
    send_put(url, data, function(json){
        if ("success" != json.status) {
            alert( json.message );
        }else{
            debugger
            if(json.articles){
                var html_content = "";
                articles = JSON.parse(json.articles)
                $(articles).each(function(){
                    //拼接一页的内容添加到展示的区域
                    html_content += '<div class="mod-b mod-art" data-aid="'+this.id+'">';
                    //html_content += '<div class="mod-angle">热</div>'
                    html_content += '<div class="mod-thumb ">'
                    html_content += '<a class="transition" title="'+this.title+'" href="article/view/'+this.id+'" target="_blank">'
                    html_content += '<img class="lazy" src="/static/sy-img/111527830443.jpg" alt="'+this.title+'">'
                    html_content += '</a>'
                    html_content += '</div>'
                    html_content += '<div class="column-link-box"><a href="javascript:void(0)" class="column-link" >'+this.category_id+'</a></div>'
                    html_content += '<div class="mob-ctt">'
                    html_content += '<h2><a href="article/view/'+this.id+'" class="transition msubstr-row2" target="_blank">'+this.title+'</a></h2>'
                    html_content += '<div class="mob-author">'
                    html_content += '<div class="author-face"><a href="article/view/'+this.id+'" target="_blank"><img src="/static/sy-img/59_1502432173.jpg"></a></div>'
                    html_content += '<a href="javascript:void(0)">'
                    html_content += '<span class="author-name ">'+this.author+'</span>'
                    html_content += '</a>'
                    html_content += '<span class="time">'+this.create_time+'</span>'
                    html_content += '<i class="icon icon-cmt"></i><em>0</em>'
                    html_content += '<i class="icon icon-fvr"></i><em>0</em>'
                    html_content += '</div>'
                    html_content +=  '<div class="mob-sub">'+this.summary+'</div>'
                    html_content +=  '</div>'
                    html_content += '</div>'
                });
                $(".mod-info-flow").html(html_content)
            }
        }
    });
}

function do_validate_login_info(){
    var login_username = $("#login_username").val();
    if( !login_username || login_username == null || login_username == "" ){
        alert("登录帐号不允许为空！");
        $("#login_username").focus();
        return false;
    }
    var login_password = $("#login_password").val();
    if( !login_password || login_password == null || login_password == "" ){
        alert("登录密码不允许为空！");
        $("#login_password").focus();
        return false;
    }
    return true;
}

function do_login(){
    var url = "login";
    var data = {
        "login_name" : $("#login_username").val(),
        "login_pwd" : $("#login_password").val()
    }
    send_post(url, data, function(json){
        if ("success" != json.status) {
            alert( json.message );
        }else{
            alert( json.message );
            // 直接访问主页，登录过后会直接把用户信息放入session
            window.location.reload();
        }
    });
}

function do_validate_user_info(){
    var p_name = $("#p_name").val();
    if( !p_name || p_name == null || p_name == "" ){
        alert("用户姓名不允许为空！");
        $("#p_name").focus();
        return false;
    }
    var p_nick_name = $("#p_nick_name").val();
    if( !p_nick_name || p_nick_name == null || p_nick_name == "" ){
        alert("用户昵称不允许为空！");
        $("#p_nick_name").focus();
        return false;
    }
    var p_email = $("#p_email").val();
    if( !p_email || p_email == null || p_email == "" ){
        alert("用户Email不允许为空！");
        $("#p_email").focus();
        return false;
    }
    return true;
}

function do_regist_new_user(){
    var url = "home/user/regist";
    var data = {
        "p_name" : $("#p_name").val(),
        "p_nick_name" : $("#p_nick_name").val(),
        "p_email" : $("#p_email").val()
    }
    $.ajax( {
        type : "POST",
        url : url,
        dataType : "json",
        contentType: "application/json",
        data : JSON.stringify(data),
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        },
        success : function ( json ) {
            if ("success" != json.status) {
                alert( json.message );
            }else{
                alert( json.message );
                // 直接访问主页，登录过后会直接把用户信息放入session
                window.location.reload();
            }
        }
    } );
}


function send_get(url, success_handled, error_handled){
    if (error_handled == null){
        error_handled = function(XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    }
    $.ajax( {
        type : "GET",
        url : url,
        error: error_handled,
        success : success_handled
    } );
}
function send_post(url, data, success_handled, error_handled){
    if (error_handled == null){
        error_handled = function(XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    }
    $.ajax( {
        type : "POST",
        url : url,
        dataType : "json",
        contentType: "application/json",
        data : JSON.stringify(data),
        error: error_handled,
        success : success_handled
    } );
}

function send_put(url, data, success_handled, error_handled){
    if (error_handled == null){
        error_handled = function(XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    }
    $.ajax( {
        type : "PUT",
        url : url,
        dataType : "json",
        contentType: "application/json",
        data : JSON.stringify(data),
        error: error_handled,
        success : success_handled
    } );
}